package com.jlnk.stockdemo.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.jlnk.stockdemo.R;
import com.jlnk.stockdemo.utils.SPUtils;
import com.jlnk.stockdemo.utils.ToastUtils;

public class ChangePasswordDialog extends Dialog {

    private EditText oldPasswordEditText;
    private EditText newPasswordEditText;
    private EditText confirmNewPasswordEditText;
    private Button changePasswordButton;

    public ChangePasswordDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_change_password);
        // 设置对话框的窗口参数
        getWindow().setLayout(800, 800); // 设置对话框的宽度和高度
        getWindow().setGravity(Gravity.CENTER); // 设置对话框居中显示
        getWindow().setBackgroundDrawableResource(R.drawable.dialog_background); // 设置圆角背景
        oldPasswordEditText = findViewById(R.id.old_password);
        newPasswordEditText = findViewById(R.id.new_password);
        confirmNewPasswordEditText = findViewById(R.id.confirm_new_password);
        changePasswordButton = findViewById(R.id.btn_change_password);
        changePasswordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String oldPassword = oldPasswordEditText.getText().toString();
                String newPassword = newPasswordEditText.getText().toString();
                String confirmNewPassword = confirmNewPasswordEditText.getText().toString();
                if (oldPassword.isEmpty()) {
                    ToastUtils.showToast("旧密码不能为空！");
                    return;
                }
                if (!oldPassword.equals(SPUtils.getPassword())) {
                    ToastUtils.showToast("旧密码错误！");
                    return;
                }
                if (newPassword.isEmpty()) {
                    ToastUtils.showToast("新密码不能为空！");
                    return;
                }
                if (confirmNewPassword.isEmpty()) {
                    ToastUtils.showToast("确认新密码不能为空！");
                    return;
                }
                if (!newPassword.equals(confirmNewPassword)) {
                    ToastUtils.showToast("新密码和确认新密码不一致！");
                    return;
                }
                changePassword(newPassword);
                dismiss();
            }
        });
    }

    private void changePassword(String newPassword) {
        SPUtils.savePassword(newPassword);
        Toast.makeText(getContext(), "密码修改成功！", Toast.LENGTH_SHORT).show();
    }
}